<template>
  <div>
    <!-- 查询表单 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="添加日期">
          <el-date-picker
            v-model="searchModel.createDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="激活日期">
          <el-date-picker
            v-model="searchModel.activeTime"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="一级代理商名称">
          <el-select
            v-model.trim="searchModel.agentFirstMasterName"
            placeholder="请选择代理商名称"
            @click="findAgent()"
          >
            <el-option
              v-for="item in agentList.data"
              :value="item['label']"
              :key="item['value']"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="一级代理商ID">
          <el-input
            v-model.trim="searchModel.agentFirstMasterId"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
            placeholder="请输入一级代理商ID"
          />
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input
            v-model.trim="searchModel.carNo"
            placeholder="请输入车牌号"
          />
        </el-form-item>
        <el-form-item label="产品序列">
          <el-input
            v-model.trim="searchModel.series"
            placeholder="请输入产品序列"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchModel.compositeState"
            class="m-2"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="推广员ID">
          <el-input
            v-model.trim="searchModel.agentId"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
            placeholder="请输入推广员ID"
          />
        </el-form-item>
      </el-form>
      <view class="subBtnBox">
        <el-button type="primary" color="#ea5b24" @click="searchOrder()"
          >查询</el-button
        >
        <el-button
          type="primary"
          color="#ea5b24"
          @click="exportOrder()"
          v-if="pinia.isShow[91]"
          >导出Excel</el-button
        >
      </view>
    </div>
    <!-- 汇总数据 -->
    <div class="div-summaryData" v-if="pinia.isShow[92]">
      <span class="text-summaryData"
        >支付订单：{{ summaryData.debitCount }}</span
      >
      <span class="text-summaryData"
        >支付金额：{{
          summaryData.debitSum ? summaryData.debitSum.toFixed(2) : "0.00"
        }}</span
      >
      <span class="text-summaryData"
        >激活订单：{{ summaryData.activeCount }}</span
      >
      <span class="text-summaryData"
        >激活金额：{{
          summaryData.activeSum ? summaryData.activeSum.toFixed(2) : "0.00"
        }}</span
      >
      <span class="text-summaryData"
        >退款订单：{{ summaryData.refundCount }}</span
      >
      <span class="text-summaryData"
        >退款金额：{{
          summaryData.refundSum ? summaryData.refundSum.toFixed(2) : "0.00"
        }}</span
      >
    </div>
    <!-- 列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column prop="createTime" width="160" label="添加日期" />
        <el-table-column
          prop="agentFirstMasterId"
          width="110"
          label="一级代理商ID"
        />
        <el-table-column
          prop="agentFirstMasterName"
          width="140"
          label="一级代理商名称"
        />
        <el-table-column prop="series" label="产品序列" />
        <el-table-column prop="carNo" label="车牌号" />
        <el-table-column prop="carColor" :formatter="judgeColor" label="颜色" />
        <el-table-column prop="totalPrice" label="订单金额" />
        <el-table-column prop="price" width="110" label="实际支付金额" />
        <el-table-column prop="compositeState" label="订单状态">
          <template #default="scope">
            <div
              :style="{
                color: scope.row.compositeState == 2 ? 'red' : 'black',
              }"
            >
              {{ judgeCompositeState(scope.row) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="active" label="激活状态">
          <template #default="scope">
            <div
              :style="{ color: scope.row.active == 1 ? '#21D86E' : 'black' }"
            >
              {{
                scope.row.active == null
                  ? ""
                  : scope.row.active == 0
                  ? "未激活"
                  : "已激活"
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="activeTime" width="160" label="激活时间" />
        <el-table-column prop="agentId" label="推广员ID" />
        <el-table-column prop="agentName" width="100" label="推广员姓名" />
        <el-table-column prop="groupName" label="所属团队" />
        <el-table-column
          prop="shangs"
          width="200"
          label="推广员上级代理线"
          show-overflow-tooltip="true"
        />
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  findBusinessOrderApi,
  findBusinessExcelApi,
  findAgentBySaleIdApi,
} from "../../../api/index";
import { formatDateTime } from "../../../utils/formatDateTime";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 翻页
let flipData = reactive({
  page: page,
  size: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.page = page.value;
  findOrder(flipData);
};
// 搜索模型
const searchModel: any = reactive({
  agentFirstMasterId: null,
  agentFirstMasterName: null,
  agentId: null,
  carNo: null,
  series: null,
  compositeState: null,
  // state: null,
  // payState: null,
  // lastRefundState: null,
  createDate: null,
  startTime: null,
  endTime: null,
  activeTime: null,
  activeStartTime: null,
  activeEndTime: null,
  page: page,
  size: size,
});

// 汇总数据
const summaryData: any = reactive({
  debitCount: null, //扣款总条数
  debitSum: null, //扣款总金额
  refundCount: null, //退款总条数
  refundSum: null, //退款总金额
  activeCount: null, //激活总条数
  activeSum: null, //激活总金额
});

// 状态枚举
const stateOptions: any = reactive([
  { value: null, label: "全部" },
  { value: "1", label: "未支付" },
  { value: "7", label: "支付中" },
  { value: "2", label: "已支付" },
  { value: "8", label: "支付失败" },
  { value: "4", label: "退款中" },
  { value: "5", label: "退款成功" },
  { value: "6", label: "退款失败" },
  { value: "9", label: "已取消" },
]);

// 判断状态显示
const judgeCompositeState = (row) => {
  switch (row.compositeState) {
    case 1:
      return "未支付";
    case 2:
      return "已支付";
    case 4:
      return "退款中";
    case 5:
      return "退款成功";
    case 6:
      return "退款失败";
    case 7:
      return "支付中";
    case 8:
      return "支付失败";
    case 9:
      return "已取消";
    default:
      return "";
  }
};

// 判断最后一次退款状态显示
const judgeLastRefundState = (row) => {
  switch (row.lastRefundState) {
    case 0:
      return "未退款";
    case 1:
      return "退款中";
    case 2:
      return "退款失败";
    case 3:
      return "退款成功";
    default:
      return "";
  }
};

// 判断颜色显示
const judgeColor = (row) => {
  switch (row.carColor) {
    case 1:
      return "黄色";
    case 2:
      return "蓝色";
    case 3:
      return "渐变绿色";
    case 4:
      return "黄绿双";
    default:
      return "";
  }
};

// 搜索业务订单
const searchOrder = () => {
  page.value = 1;
  if (searchModel.createDate) {
    searchModel.startTime = formatDateTime(searchModel.createDate[0]);
    searchModel.endTime = formatDateTime(searchModel.createDate[1]).replace(
      "00:00:00",
      "23:59:59"
    );
  } else {
    searchModel.startTime = null;
    searchModel.endTime = null;
  }
  if (searchModel.activeTime) {
    searchModel.activeStartTime = formatDateTime(searchModel.activeTime[0]);
    searchModel.activeEndTime = formatDateTime(
      searchModel.activeTime[1]
    ).replace("00:00:00", "23:59:59");
  } else {
    searchModel.activeStartTime = null;
    searchModel.activeEndTime = null;
  }
  searchParmSearch();
  findOrder(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 查询代理信息
let agentList: any = reactive([]);
const findAgent = () => {
  findAgentBySaleIdApi().then((res) => {
    if (res.data.code === 2000) {
      let dataList = res.data.data;
      dataList.unshift({ agentId: null, agentName: "全部" });
      agentList.data = Array.from(dataList).map((item, idx) => ({
        value: item["agentId"],
        label: item["agentName"],
      }));
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 查询业务订单
const findOrder = (searchModel) => {
  if (searchModel.agentFirstMasterName == "全部")
    searchModel.agentFirstMasterName = null;
  findBusinessOrderApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      if (res.data.data) {
        tableData.data = res.data.data.pager.data;
        totalNum.value = res.data.data.pager.total;
      } else {
        tableData.data = null;
        totalNum.value = null;
      }
      summaryData.debitCount = res.data.data.debitCount ?? 0;
      summaryData.debitSum = res.data.data.debitSum ?? 0;
      summaryData.refundCount = res.data.data.refundCount ?? 0;
      summaryData.refundSum = res.data.data.refundSum ?? 0;
      summaryData.activeCount = res.data.data.activeCount ?? 0;
      summaryData.activeSum = res.data.data.activeSum ?? 0;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

//导出订单
const exportOrder = () => {
  findBusinessExcelApi(searchModel).then((res) => {
    const blob = new Blob([res.data]);
    const fileName = "业务订单数据.xls";
    const elink = document.createElement("a"); // 创建a标签
    elink.download = fileName; // 为a标签添加download属性
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click(); // 点击下载
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink); // 释放标签
  });
};

onMounted(() => {
  findOrder(searchModel);
});
</script>

<style scoped>
:deep(.demo-form-inline) {
  display: grid;
  justify-items: stretch;
  grid-template-columns: repeat(auto-fill, 25%);
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-form-item) {
  width: 90%;
}

.subBtnBox {
  width: 100%;
  margin-bottom: 20px;
  display: block;
  text-align: center;
}

:deep(.el-dialog__body) {
  padding: 13px 104px 18px 103px;
}

.item__txt {
  box-sizing: border-box;
  line-height: 24px;
  padding: 0 9px;
}

.div-summaryData {
  background-color: rgb(187, 190, 195);
  height: 34px;
  margin-top: 20px;
  line-height: 33px;
}

.text-summaryData {
  color: black;
  font-size: 14px;
  margin-right: 30px;
  margin-left: 10px;
}
</style>
